package tr.edu.yildiz.appagentandroid.service;

import tr.edu.yildiz.ce.dap.appagent.exception.AgentCommunicationException;
import tr.edu.yildiz.ce.dap.appagent.service.infra.NetworkManager;
import tr.edu.yildiz.ce.dap.appagentinfra.service.NetworkManagerImpl;
import tr.edu.yildiz.crystalapp.infra.InfraManager;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.net.wifi.WifiManager.WifiLock;

public class AndroidNetworkManagerImpl extends InfraManager implements NetworkManager{
	
	NetworkManager networkManager = new NetworkManagerImpl();

	static MulticastLock mLock = null;
	static WifiLock wLock  = null;
	
	private MulticastLock initMulticastLock(){
		if (mLock == null){
			WifiManager wifiManager = (WifiManager) activity.getSystemService(activity.getApplicationContext().WIFI_SERVICE);
			mLock = wifiManager.createMulticastLock("mLock");
			mLock.acquire();
		}
        return mLock;
	}
	
	private WifiLock initWifiLock(){
		if (wLock == null && mLock == null){
			WifiManager wifiManager = (WifiManager) activity.getSystemService(activity.getApplicationContext().WIFI_SERVICE);
			wLock = wifiManager.createWifiLock("wLock");
			wLock.acquire();
		}
        return wLock;
	}
	
	public void listen(MessageReceivedCallBack mrCallBack, int port) {
		networkManager.listen(mrCallBack, port);
	}

	public String joinMulticast(String multicastAddress, int port)
			throws AgentCommunicationException {
		initMulticastLock();
		String s = networkManager.joinMulticast(multicastAddress, port);
		return s;
	}

	public String sendMessage(String message, String address, int port)
			throws AgentCommunicationException {
		initWifiLock();
		String s = networkManager.sendMessage(message, address, port);
		return s ;
	}
	


	
}
